<?php
/**
 * Model 管理器
 * 建立 表名称到 model 的映射关系，并根据表名获取 model
 */
class CModelManager{
	
	/**
	 * 规则列表
	 */
	private static $_regulars = array();
	
	/**
	 * 添加规则
	 * @param String $modelName model的名称
	 * @param String $regular 正则，自动添加头尾
	 * @param Boolean $isString 规则是否为字符串
	 */
	public static function addRule($modelName, $regular, $isString = false) {
		$hash = md5($modelName.$regular);
		
		if(isset(self::$_regulars[$hash])) return;
		
		self::$_regulars[$hash] = array('regular'=>$regular, 'modelName'=> $modelName, 'isString'=> $isString);
	}
	
	/**
	 * 根据表名，查询model
	 */
	public static function get($tableName) {
		$modelName = '';
		
		foreach(self::$_regulars as $item) {
			if($item['isString']) {
				if($tableName == $item['regular']) {
					$modelName = $item['modelName'];
					break;
				}
			} else {
				$regular = sprintf("/^%s$/", $item['regular']);
				if(preg_match($regular, $tableName)) {
					$modelName = $item['modelName'];
					break;
				}
			}
		}
		
		if($modelName) return $modelName;
		
		return ucfirst(preg_replace_callback("#_(\w)#", function($match) {
			return ucfirst($match[1]);
		}, $tableName));
	}
}